package com.siyoumi.app.modules.sys_status.web;

import com.siyoumi.app.netty.NettyMqttUtil;
import com.siyoumi.app.modules.sys_status.entity.SysStatusInfo;
import com.siyoumi.component.XRedis;
import com.siyoumi.controller.ApiController;
import com.siyoumi.service.SysAppService;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//系统状态
@Slf4j
@RestController
@RequestMapping("/app/sys_status")
public class sys_status
        extends ApiController {

    @GetMapping("")
    public SysStatusInfo index() {
        SysStatusInfo sysStatusInfo = new SysStatusInfo();

        log.info("check redis");
        try {
            XRedis.getBean().setEx("test", "1", 5);
            sysStatusInfo.setRedis_status(true);
        } catch (Exception ex) {
            sysStatusInfo.setRedis_status(false);
            sysStatusInfo.setRedis_errmsg(ex.getMessage());
        }

        log.info("check mysql");
        try {
            SysAppService.getBean().getEntity("1");
            sysStatusInfo.setMysql_status(true);
        } catch (Exception ex) {
            sysStatusInfo.setMysql_errmsg(ex.getMessage());
        }

        return sysStatusInfo;
    }


    @GetMapping("mqtt")
    public XReturn mqtt() {
        String action = input("action", "");
        String pin = input("pin", "2");
        String pinAction = input("pin_action", "0");
        String pinMode = input("pin_mode", "out");

        XReturn r = XReturn.getR(0);

        Map<String, Channel> mapChannel = NettyMqttUtil.getMapChannel();
        r.setData("size", mapChannel.size());
        List<String> key = mapChannel.entrySet().stream().map(item -> item.getKey()).collect(Collectors.toList());
        r.setData("channel", key);

        Channel channelFrist = null;
        for (Map.Entry<String, Channel> entry : mapChannel.entrySet()) {
            channelFrist = entry.getValue();
            break;
        }

        XReturn rr = XReturn.getR(0);
        rr.setData("action", action);
        rr.setData("pin", XStr.toInt(pin));
        rr.setData("pin_mode", pinMode);
        rr.setData("pin_action", XStr.toInt(pinAction));
        NettyMqttUtil.sendMessage(channelFrist, "siyoumi", XJson.toJSONString(rr));

        return r;
    }
}
